// pages/control_sell/control_sell.js
const db = wx.cloud.database()
const app=getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    shops:null,
    src:[]
  },
  onLoad: function (options) {
    let that=this;
    db.collection('users').where({
      _openid: app.globalData.openid // 填入当前用户 openid
    }).get().then(res => {
      console.log(res.data);
      that.setData({
        shops:res.data
      })
      that.getPiture();
    })
  },
  //获得照片
  getPiture:function(){
    let that=this;
    let len=this.data.shops.length;
    let srcs=[...that.data.shops];
    let oldsrc;
    for(var i=0;i<len;i++){
      //从云存储里面下载文件
      wx.cloud.getTempFileURL({
        fileList: [{
          fileID: srcs[i].src,
          maxAge: 60 * 60, 
        }]
      }).then(res => {
        oldsrc = [...that.data.src];
        if(oldsrc.length==0){
          that.setData({
            src: [res.fileList[0].tempFileURL]
          })
        }else{
          that.setData({
            src: [...oldsrc,res.fileList[0].tempFileURL]
          })
        }
      })
    }
  },
  dowm_shop:function(e){
    let id=e.currentTarget.dataset.id;
    let src = e.currentTarget.dataset.src;
    console.log(src)
    let that=this;
    let len=that.data.shops.length;

    //删除商品信息
    db.collection('users').doc(id).remove()
      .then(console.log)
      .catch(console.error)
      //删除商品照片

    wx.cloud.deleteFile({
      fileList: [src]
    }).then(res => {
      console.log(res)
      wx.showToast({
        title: '等待中',
      })
      console.log(res.fileList)
    }).catch(error => {
    })
    db.collection('users').where({
      _openid: app.globalData.openid // 填入当前用户 openid
    }).get().then(es => {
      console.log(es)
      that.setData({
        shops: es.data
      })
      that.getPiture();
    })
  },
  update:function(e){
    let id = e.currentTarget.dataset.id;
    let src = e.currentTarget.dataset.src;
    wx.navigateTo({
      url: '../reset_shopping/reset_shopping?id=' + id + "&src=" + src
    })
  },
  //更新页面信息
  onShow: function () {
    this.onLoad()
  },
})